package com.huangfuyi.process.actuator.monitor;

import com.huangfuyi.process.actuator.enums.EPMonitorThreadStatus;
import com.huangfuyi.process.entity.monitor.EPMonitorAliveCheckInfo;
import com.huangfuyi.process.entity.monitor.EPMonitorInfo;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;

/**
 * 线程存活性监控线程，用于监控其他核心线程是否正常运行
 */
public class EPMonitorAliveCheckThread extends EPMonitorThread<List<EPMonitorAliveCheckInfo>> {

    private static final Logger log = Logger.getLogger("AliveCheckThread");

    public EPMonitorAliveCheckThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        // 当前线程被标记为销毁时，不再继续循环
        while (!this.isDestruction()) {
            EPMonitorInfo<List<EPMonitorAliveCheckInfo>> monitorInfo = this.getMonitorInfo();

            // 更新本次运行信息
            monitorInfo.setStatus(EPMonitorThreadStatus.RUNNING);
            monitorInfo.setStartTime(System.currentTimeMillis());

            // 进行监控存活性检测
            ArrayList<EPMonitorAliveCheckInfo> checkResults = new ArrayList<>();
            try {
                EPMonitorThreadManager.aliveCheck(checkResults);
                monitorInfo.setSuccess(true);
                monitorInfo.setMessage("存活性检测： 检测成功");
                log.info("存活性检测： 检测成功");
            } catch (Throwable t) {
                StringWriter stackInfo = new StringWriter();
                t.printStackTrace(new PrintWriter(stackInfo));
                monitorInfo.setSuccess(false);
                monitorInfo.setMessage(stackInfo.toString());
                log.warning(String.format(Locale.ROOT, "存活性检测： 运行失败！原因：%s", monitorInfo.getMessage()));
            }

            monitorInfo.setData(checkResults);

            // 检测执行完成后，更新线程运行信息
            monitorInfo.setStatus(EPMonitorThreadStatus.FINISH);
            monitorInfo.setEndTime(System.currentTimeMillis());

            try {
                sleep(monitorInfo.getRunInterval());
            } catch (InterruptedException e) {
                log.warning(String.format(Locale.ROOT, "存活性检测： 等待唤醒失败！原因：%s", e.getMessage()));
                setDestruction(true);
            }
        }


    }
}
